package com.googlecode.chelonia;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.ws.commons.util.Base64;

import com.googlecode.jj1.server.JsonRpc;

public class AfricaRpc {
	private static SessionContainer<MapImage> sessions = new SessionContainer<MapImage>();

	@JsonRpc
	public String create(int width, int height) {
		String key = null;
		MapImage mi = new MapImage(width, height);
		while (key == null) {
			key = sessions.create(mi);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {

			}
		}
		return key;
	}

	@JsonRpc
	public String setBackground(String key, String color) {
		MapImage i = get(key);
		i.setBackground(new Color(Integer.parseInt(color, 16)));
		return key;
	}

	@JsonRpc
	private MapImage get(String key) {
		MapImage i = sessions.get(key);
		if (i == null) {
			throw new RuntimeException("session timed out");
		}
		return i;
	}

	@JsonRpc
	public String paintCountries(String key, String color, String countriesList) {
		CountrySet countries = new CountrySet(countriesList);
		Color col = new Color(Integer.parseInt(color, 16));
		MapImage i = get(key);
		i.paintCountries(col, countries);
		return key;
	}

	@JsonRpc
	public String paintBorders(String key, String color, String countriesList, double lineWidth) {
		CountrySet countries = new CountrySet(countriesList);
		Color col = new Color(Integer.parseInt(color, 16));
		MapImage i = get(key);
		i.paintBorders(col, countries, (float) lineWidth);
		return key;
	}

	@JsonRpc
	public String toBase64Image(String key, String extension) {
		byte[] data = toImage(key, extension);
		return Base64.encode(data);
	}

	public byte[] toImage(String key, String extension) {
		MapImage mi = get(key);
		sessions.remove(key);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		mi.toImage(extension, baos);
		byte[] data = baos.toByteArray();
		try {
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

}
